<?php
/**
 * FileName: Category.php
 * Author: Fei.Song
 * Date: 2021/5/25 23:11
 * Created by PhpStorm
 * Desc:
 */

namespace App\Models;

class Category extends BaseModel {
    protected $table = "category";
    protected $fillable = ['parent_id', 'name', 'group_id', 'icon', 'code', 'sort', 'site_id', 'description','scope_course','scope_exam'];
    protected $casts = [
        'created_at' => 'datetime:Y-m-d',
        'updated_at' => 'datetime:Y-m-d',
    ];
    protected $declares = [
        "id"=>["id","="],
        "name"=>["name","="],
        "parent_id"=>["parent_id","="],
        "site_id" => ["site_id", "="],
        "group_id" => ["group_id", "="],
        "status" => ["status", "="],
    ];
    protected $with = ['courseTagGroup:id,name', 'examTagGroup:id,name','version'];

    public function courseTagGroup() {
        return $this->belongsToManyTagGroup('course');
    }

    public function examTagGroup() {
        return $this->belongsToManyTagGroup('exam');
    }

    public function getCourseTagGroupAttribute() {
        return $this->hasTagGroupByType('course');
    }

    public function getExamTagGroupAttribute() {
        return $this->hasTagGroupByType('exam');
    }

    private function belongsToManyTagGroup($tagType) {
        return $this->belongsToMany("App\Models\TagGroup", 'category_tag_group', 'category_id', 'tag_group_id')->wherePivot('tag_type',$tagType);
    }

    private function hasTagGroupByType($tagType) {
        return $this->belongsToManyTagGroup($tagType)->get(['id', 'name'])->keyBy('id');
    }

    public function tagGroupsAndTags($tagType) {

    }

    /**
     * 关联版本(多对多)
     */
    public function version(){
        return $this->belongsToMany("App\Models\QuestionVersion","category_version","category_id","version_id")->withPivot(["default","usable"]);
    }
}
